import { prefixAuth as PREFIX_AUTH } from '@/env'

export const redirectTo = url => {
  window.location.href = url
}

export const isNumeric = value => {
  return !isNaN(parseFloat(value)) && isFinite(value)
}

function extend (to, from) {
  for (let key in from) {
    to[key] = from[key]
  }
  return to
}

export const toObject = arr => {
  const res = {}
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]) {
      extend(res, arr[i])
    }
  }
  return res
}
// form: {child: { child_1: 0}}
// child.child_1 求值
export function getPropByPath (obj, path, strict) {
  let tempObj = obj
  path = path.replace(/\[(\w+)\]/g, '.$1')
  path = path.replace(/^\./, '')

  let keyArr = path.split('.')
  let i = 0
  for (let len = keyArr.length; i < len - 1; ++i) {
    if (!tempObj && !strict) break
    let key = keyArr[i]
    if (key in tempObj) {
      tempObj = tempObj[key]
    } else {
      if (strict) {
        throw new Error('please transfer a valid prop path to form item')
      }
      break
    }
  }
  return {
    o: tempObj,
    k: keyArr[i],
    v: tempObj ? tempObj[keyArr[i]] : null
  }
}

export const arrayFindIndex = function (arr, pred) {
  for (let i = 0; i !== arr.length; ++i) {
    if (pred(arr[i])) {
      return i
    }
  }
  return -1
}

export const coerceTruthyValueToArray = function (val) {
  if (Array.isArray(val)) {
    return val
  } else if (val) {
    return [val]
  } else {
    return []
  }
}

export const createAuthString = (prefixAuth, action) => {
  action = typeof action === 'string' ? action.split(/ +/g) : action
  return action.reduce((t, n) => {
    t[n] = `${PREFIX_AUTH}.${prefixAuth}:${n}`
    return t
  }, {})
}
